﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using RbacPermissionManage.DoMain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RbacPermissionManage.Repository
{
    public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private readonly RbacDbContext _db;
        private readonly IHttpContextAccessor httpContext;

        public Repository(RbacDbContext db, IHttpContextAccessor httpContext)
        {
            _db = db;
            this.httpContext = httpContext;
        }


        #region 添加
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<TEntity> InsertAsync(TEntity entity)
        {
            Type entityType = entity.GetType();
            PropertyInfo createdTimeProperty = entityType.GetProperty("CreateTime");
            PropertyInfo createdNameProperty = entityType.GetProperty("CreateName");
            string UserName = httpContext.HttpContext.User.Identity.Name;
            createdTimeProperty?.SetValue(entity, DateTime.Now);
            createdNameProperty?.SetValue(entity, UserName);

            _db.Set<TEntity>().Add(entity);
            await _db.SaveChangesAsync();
            return entity;
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public async Task<int> InsertAsync(List<TEntity> entities)
        {
            await _db.Set<TEntity>().AddRangeAsync(entities);
            return await _db.SaveChangesAsync();
        }
        #endregion

        #region 更新
        /// <summary>
        /// 根据实体更新
        /// </summary>
        /// <param name="PrimarkKey"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<TEntity> UpdateAsync(int PrimarkKey, TEntity entity)
        {
            var currEntity = await _db.Set<TEntity>().FindAsync(PrimarkKey);
            _db.Set<TEntity>().Update(entity);
            await _db.SaveChangesAsync();
            return entity;
        }

        /// <summary>
        /// 根据实体更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<TEntity> UpdateAsync(TEntity entity)
        {
            _db.Set<TEntity>().Update(entity);
            await _db.SaveChangesAsync();
            return entity;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        public async Task<int> SaveChangesAsync()
        {
            // 通过获取当前数据库上下文对象，调用 SaveChangesAsync() 方法保存更改
            return await _db.SaveChangesAsync();
        }

        #endregion

        #region 删除
        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="PrimarkKey"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(int PrimarkKey)
        {
            var entity = await _db.Set<TEntity>().FindAsync(PrimarkKey);
            _db.Set<TEntity>().Remove(entity);
            return await _db.SaveChangesAsync();
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="PrimaryKeys"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(List<int> PrimaryKeys)
        {
            foreach (var item in PrimaryKeys)
            {
                var entity = await _db.Set<TEntity>().FindAsync(item);
                _db.Set<TEntity>().Remove(entity);
            }
            return await _db.SaveChangesAsync();
        }

        /// <summary>
        /// 按条件删除
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate)
        {
            var entitys = _db.Set<TEntity>().Where(predicate);
            foreach (var item in entitys)
            {
                _db.Set<TEntity>().Remove(item);
            }
            return await _db.SaveChangesAsync();
        }
        #endregion

        #region 查询
        /// <summary>
        /// 按主键查
        /// </summary>
        /// <param name="PrimaryKey"></param>
        /// <returns></returns>
        public async Task<TEntity> FindAsync(int PrimaryKey)
        {
            return await _db.Set<TEntity>().FindAsync(PrimaryKey);
        }

        /// <summary>
        /// 按条件查单条
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await _db.Set<TEntity>().FirstOrDefaultAsync(predicate);
        }

        /// <summary>
        /// 查全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<TEntity>> QueryAsync()
        {
            return await _db.Set<TEntity>().ToListAsync();
        }

        /// <summary>
        /// 查全部
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> predicate = null)
        {
            return await _db.Set<TEntity>().Where(predicate).ToListAsync();
        }

        /// <summary>
        /// 返回IQueryable
        /// </summary>
        /// <returns></returns>
        public IQueryable<TEntity> Queryable()
        {
            return _db.Set<TEntity>();
        }

        /// <summary>
        /// 判断是否存在该数据
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<bool> IsExistsAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await _db.Set<TEntity>().AnyAsync(predicate);
        }
        #endregion
    }
}
